package com.example.demo.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.demo.base.login.dto.LoginVo;
import com.example.demo.base.permission.dto.UserRoleDto;
import com.example.demo.constants.RedisKey;
import com.example.demo.domain.entity.PermissionFrontUrl;
import com.example.demo.domain.entity.PermissionUrl;
import com.example.demo.domain.entity.RolePermission;
import com.example.demo.domain.entity.User;
import com.example.demo.domain.entity.UserRole;
import com.example.demo.exception.ValidatorException;
import com.example.demo.mapper.PermissionUrlMapper;
import com.example.demo.mapper.RolePermissionMapper;
import com.example.demo.param.UserRoleParam;
import com.example.demo.service.UserRoleService;
import com.example.demo.mapper.UserRoleMapper;
import com.example.demo.utils.RedisUtil;
import com.example.demo.utils.ValidatorUtil;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
* @author 00774904
* @description 针对表【user_role(用户角色)】的数据库操作Service实现
* @createDate 2023-11-09 17:46:49
*/
@Service
public class UserRoleServiceImpl extends ServiceImpl<UserRoleMapper, UserRole>
    implements UserRoleService{

    @Resource
    private UserRoleMapper userRoleMapper;

    @Resource
    private RolePermissionMapper rolePermissionMapper;

    @Resource
    private PermissionUrlMapper permissionUrlMapper;

    @Resource
    private RedisUtil redisUtil;

    @Transactional
    @Override
    public void createUserRole(UserRoleDto userRoleDto) {
        saveUserRole(userRoleDto);
    }


    @Transactional
    @Override
    public void updateUserRole(UserRoleDto userRoleDto) {
        if (null == userRoleDto.getId()){
            throw new ValidatorException("角色id不能为空");
        }

        UserRole userRole = userRoleMapper.selectById(userRoleDto.getId());
        if (null == userRole){
            throw new ValidatorException("角色不存在");
        }
        UserRoleDto(userRoleDto,userRole);
        userRoleMapper.updateById(userRole);

        QueryWrapper<RolePermission> queryWrapper = new QueryWrapper<RolePermission>();
        queryWrapper.eq("role_id",userRole.getId());
        rolePermissionMapper.delete(queryWrapper);
        // 修改redis
        List<Long> fIds = new ArrayList<>();
        for (RolePermission rolePermission : userRoleDto.getRolePermissionList()) {
            rolePermission.setRoleId(userRole.getId());
            rolePermission.setfId(rolePermission.getfId());
            rolePermission.setPermissionComent(rolePermission.getPermissionComent());
            rolePermissionMapper.insert(rolePermission);
            fIds.add(rolePermission.getfId());
        }

        // 更新redis
        if (CollectionUtil.isEmpty(fIds)){
            QueryWrapper<PermissionUrl> queryWrapper1 = new QueryWrapper<PermissionUrl>();
            queryWrapper1.in("f_id",fIds);
            List<PermissionUrl> permissionUrls = permissionUrlMapper.selectList(queryWrapper1);
            if (!CollectionUtil.isEmpty(permissionUrls)){
                List<String> strings = new ArrayList<>();
                for (PermissionUrl permissionUrl : permissionUrls) {
                    if (!strings.contains(permissionUrl.getBackUrl())){
                        strings.add(permissionUrl.getBackUrl());
                    }
                }
                redisUtil.delKey(RedisKey.REDIS_PERMISSION_BACK_URL_SET.concat(String.valueOf(userRole.getId())));
                redisUtil.setKeyOfList(RedisKey.REDIS_PERMISSION_BACK_URL_SET.concat(String.valueOf(userRole.getId())),strings);
            }
        }
    }

    private void UserRoleDto(UserRoleDto userRoleDto,UserRole userRole){
        userRole.setId(userRoleDto.getId());
        userRole.setRoleName(userRoleDto.getRoleName());
        userRole.setRoleComent(userRoleDto.getRoleComent());
        userRole.setCId(userRoleDto.getcId());
    }

    @Override
    public void deleteUserRole(UserRoleDto userRoleDto) {
        dropUserRole(userRoleDto);
    }

    @Override
    public Page<UserRole> queryeUserRole(UserRoleParam userRoleParam) {
        QueryWrapper<UserRole> queryWrapper = new QueryWrapper<UserRole>();

        if (null != userRoleParam.getcId()){
            queryWrapper.eq("c_id",userRoleParam.getcId());
        }

        if (null != userRoleParam.getId()){
            queryWrapper.eq("id",userRoleParam.getId());
        }

        if (null != userRoleParam.getRoleName()){
            queryWrapper.like("role_name",userRoleParam.getRoleName());
        }

        Page<UserRole> page = new Page<>(userRoleParam.getPageNumber(), userRoleParam.getPageSize());

        return userRoleMapper.selectPage(page,queryWrapper);
    }


    private void validUserRoleDto(UserRoleDto userRoleDto){
        ValidatorUtil.require(userRoleDto.getRoleName(),"角色名称");
        ValidatorUtil.require(userRoleDto.getcId(),"公司");
    }


    private void saveUserRole(UserRoleDto userRoleDto) {

        validUserRoleDto(userRoleDto);
        // 新增用户角色

        QueryWrapper<UserRole> queryWrapper = new QueryWrapper<UserRole>();
        queryWrapper.eq("c_id",userRoleDto.getcId());
        queryWrapper.eq("role_name",userRoleDto.getRoleName());
        UserRole userRole1 = userRoleMapper.selectOne(queryWrapper);
        if (null != userRole1){
            throw new ValidatorException("同一个公司内，角色名不能相同");
        }

        UserRole userRole = new UserRole();
        userRole.setCId(userRoleDto.getcId());
        userRole.setRoleComent(userRoleDto.getRoleComent());
        userRole.setRoleName(userRoleDto.getRoleName());
        userRoleMapper.insert(userRole);


        List<Long> fIds = new ArrayList<>();
        for (RolePermission rolePermission : userRoleDto.getRolePermissionList()) {
            rolePermission.setRoleId(userRole.getId());
            rolePermission.setfId(rolePermission.getfId());
            rolePermission.setPermissionComent(rolePermission.getPermissionComent());
            rolePermissionMapper.insert(rolePermission);
            fIds.add(rolePermission.getfId());
        }

        // 更新redis
        if (CollectionUtil.isEmpty(fIds)){
            QueryWrapper<PermissionUrl> queryWrapper1 = new QueryWrapper<PermissionUrl>();
            queryWrapper1.in("f_id",fIds);
            List<PermissionUrl> permissionUrls = permissionUrlMapper.selectList(queryWrapper1);
            if (!CollectionUtil.isEmpty(permissionUrls)){
                List<String> strings = new ArrayList<>();
                for (PermissionUrl permissionUrl : permissionUrls) {
                    if (!strings.contains(permissionUrl.getBackUrl())){
                        strings.add(permissionUrl.getBackUrl());
                    }
                }
                redisUtil.delKey(RedisKey.REDIS_PERMISSION_BACK_URL_SET.concat(String.valueOf(userRole.getId())));
                redisUtil.setKeyOfList(RedisKey.REDIS_PERMISSION_BACK_URL_SET.concat(String.valueOf(userRole.getId())),strings);
            }
        }

    }

    private void dropUserRole(UserRoleDto userRoleDto){
        if (null == userRoleDto.getId()){
            throw new ValidatorException("角色id不能为空");
        }

        UserRole userRole = userRoleMapper.selectById(userRoleDto.getId());
        if (null == userRole){
            throw new ValidatorException("角色不存在");
        }

        // 不考虑并发，只有管理员可以修改，先删除后修改
        userRoleMapper.deleteById(userRole.getId());
        QueryWrapper<RolePermission> queryWrapper = new QueryWrapper<RolePermission>();
        queryWrapper.eq("role_id",userRole.getId());
        rolePermissionMapper.delete(queryWrapper);

        redisUtil.delKey(RedisKey.REDIS_PERMISSION_BACK_URL_SET.concat(String.valueOf(userRole.getId())));
    }
}




